import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/state_manager.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../apis/alarm.dart';
import '../../../apis/base.dart';
import '../../../apis/elevator.dart';
import '../../../apis/notice.dart';
import '../../../components/status/toast.dart';
import '../../../controller/gather_ctrl.dart';
import '../../../controller/notice_ctrl/notice_ctrl.dart';
import '../../../model/bean/alarm_bean.dart';
import '../../../model/bean/community_bean.dart';
import '../../../model/bean/login_info.dart';
import '../../../model/bean/manage_elevator_num_bean.dart';
import '../../../router/router.dart';
import '../components/navs.dart';

class HomeCtrl extends GatherCtrl {
  // 组件是否初始化完成
  RxBool isInitComplete = false.obs;

  // 下拉刷新数据控制器
  final Rx<RefreshController> refreshs = RefreshController().obs;

  // 登录者
  final RxString userName = LoginInfo.userInfo.username.obs;

  // 小区数据集合
  final communityData = Rx<List<DropdownMenuItem<CommunityBean>>>();

  // 用户管理的电梯数量
  final RxInt elevatorsCount = 0.obs;

  // 近期告警
  final Rx<AlarmListBean> listData = AlarmListBean().obs;

  @override
  void onInit() {
    // 合发请求
    multipleRequests();
  }

  @override
  void modify() => print("网络不可用");

  /// 读取小区列表
  /// * [callback] Function|回调函数|选填{Function callback}
  Future<bool> readCommunityList() async {
    try {
      // 获取小区列表数据
      await Base.queryCommunity();

      print(CommunityListBean.getCommunity);
    } catch (e) {
      Toast.fail(title: '小区获取失败');
    }

    return true;
  }

  /// 同时发送（多条）请求
  Future<bool> multipleRequests() async {
    await Future.wait<dynamic>([
      readAlarmList(),
      readUnreadMsg(),
      readManageElevatorNum(),
      readCommunityList(),
    ])
        .then(
          (value) => value,
        )
        .catchError(
          (e) => e,
        );

    // 标记页面加载状态（初始化时候启用）
    if (!isInitComplete.value) isInitComplete.value = true;

    // 执行完成（无论成功与否）
    return true;
  }

  /// 获取近期告警信息
  Future<bool> readAlarmList() async {
    // 执行请求操作
    AlarmListBean result = await Alarm.getAlarmList({
      "villageIds": "",
      "status": "",
      "startDate": "",
      "endDate": "",
      "page": 1,
      "rows": 10,
    });

    // 检查返回结果
    if (result != null) {
      listData.value = result;
      return true;
    } else {
      return false;
    }
  }

  /// 获取消息
  Future<bool> readUnreadMsg() async {
    NoticeCtrl result = await Notice.queryUnreadMsg();
//    print(messagesCount.messagesCount.value);
    if (result != null) {
      //print("${NoticeCtrl.messagesCount.value}--我是home控制器");
      //messagesCount.value = result;
      return true;
    } else {
      return false;
    }
  }

  /// 获取管理的添加数量
  Future<bool> readManageElevatorNum() async {
    ManageElevatorNumBean result = await Elevator.queryManageElevatorNum();
    if (result != null) {
      elevatorsCount.value = result.elevatorsCount;
      return true;
    } else {
      return false;
    }
  }

  /// 更新操作
  void onRefresh() async {
    await multipleRequests();
    Timer(Duration(seconds: 1), () {
      refreshs.value.refreshCompleted();
    });
  }

  /// 快速导航
  /// * [type] NavType|导航去向|必填
  void quickNavigation(NavType type) {
    switch (type) {
      case NavType.MYELEVATOR:
        Get.toNamed(AppRoutes.LiftManage);
        break;
      case NavType.ALARMMANAGEMENT:
        Get.toNamed(AppRoutes.AlarmRecord);
        break;
      case NavType.MAINTENANCEPLAN:
        Get.toNamed(AppRoutes.Plan);
        break;
      case NavType.MAINTENANCERECORD:
        Get.toNamed(AppRoutes.ToDayTodo);
        break;
      case NavType.REPAIR:
        Get.toNamed(AppRoutes.RepairsList);
        break;
    }
  }

  /// 离开当前页面，记录返回动作
  /// * [arg] Map<String, dynamic>|路由跳转|必填
  void onLeave(Map<String, dynamic> arg) {
    Get.toNamed(
      AppRoutes.LiftDetails,
      arguments: arg,
    ).then((value) => null);
  }
}
